package com.hellobike.haxing.modules.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.product.entity.Sku;
import com.hellobike.haxing.modules.product.entity.Spu;
import com.hellobike.haxing.modules.product.entity.SpuAuditLog;
import com.hellobike.haxing.modules.product.entity.Unit;
import com.hellobike.haxing.modules.product.exception.ProductException;
import com.hellobike.haxing.modules.product.service.ISkuService;
import com.hellobike.haxing.modules.product.service.ISpuAuditLogService;
import com.hellobike.haxing.modules.product.service.ISpuService;
import com.hellobike.haxing.modules.product.service.IUnitService;
import com.hellobike.haxing.modules.supplier.entity.TSupplierClPro;
import com.hellobike.haxing.modules.supplier.service.ITSupplierClProService;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: SPU
 * @Author: haxing-boot
 * @Date: 2020-01-10
 * @Version: V1.0
 */
@RestController
@RequestMapping("/product/spu")
@Slf4j
public class SpuController extends BaseController<Spu, ISpuService> {
    @Autowired
    private ISpuService spuService;
    @Autowired
    private ISkuService skuService;
    @Autowired
    private ISpuAuditLogService spuAuditLogService;
    @Autowired
    private ITSupplierClProService supplierClProService;
    @Autowired
    private IUnitService unitService;

    /**
     * 分页列表查询
     *
     * @param spu
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "SPU-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(Spu spu,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<Spu> queryWrapper = QueryGenerator.initQueryWrapper(spu, req.getParameterMap());
        Page<Spu> page = new Page<Spu>(pageNo, pageSize);
        IPage<Spu> pageList = spuService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param spu
     * @return
     */
    @AutoLog(value = "SPU-添加", operateType = 2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody Spu spu) {
        try {
            spuService.saveSpu(spu);
            return Result.ok("添加成功!");
        } catch (ProductException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 编辑
     *
     * @param spu
     * @return
     */
    @AutoLog(value = "SPU-编辑", operateType = 3)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody Spu spu) {
        try {
            spuService.updateSpu(spu);
            return Result.ok("编辑成功!");
        } catch (ProductException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "SPU-删除", operateType = 4)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) Long id) {
        spuService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "SPU-批量删除", operateType = 4)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.spuService.removeByIds(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) Long id) {
        Spu spu = spuService.getSpuDetail(id);
        if (spu == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(spu);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param spu
     */
    @AutoLog(value = "SPU-导出excel", operateType = 6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Spu spu) {
        return super.exportXls(request, spu, Spu.class, "SPU");
    }

    /**
     * 通过excel导入数据
     * @param file
     * @return
     */
    @AutoLog(value = "SPU-导入excel", operateType = 5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(@RequestParam(value = "file") MultipartFile file) {
        try {
            spuService.importSpus(file);
            return Result.ok("导入成功");
        } catch (ProductException e) {
            return Result.error(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("系统错误！");
        }
    }

    /**
     * 下载导入模板
     * @param response
     * @throws IOException
     */
    @GetMapping("/downloadImportTemplate")
    public void downloadImportTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=spu_import_template.xlsx");// 设置文件名
        ClassPathResource classPathResource = new ClassPathResource("templates/spu_import_template.xlsx");
        @Cleanup InputStream is = classPathResource.getInputStream();
        @Cleanup BufferedInputStream bis = new BufferedInputStream(is);
        @Cleanup OutputStream os = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) > 0) {
            os.write(buffer, 0, len);
        }
        response.flushBuffer();
    }

    /**
     * 提交审核
     * @param id
     * @return
     */
    @GetMapping("/submitAudit")
    public Result<?> submitAudit(@RequestParam(name = "id", required = true) Long id) {
        Spu spu = spuService.getById(id);
        if (spu.getStatus() != 1 && spu.getStatus() != 4) {
            return Result.error("当前状态不允许提交审核");
        }
        Spu updateModel = new Spu();
        updateModel.setId(id);
        updateModel.setStatus(2);
        spuService.updateById(updateModel);
        return Result.ok();
    }

    /**
     * 审核SPU
     * @param spuAuditLog
     * @return
     */
    @PostMapping(value = "auditSpu")
    public Result<?> auditSpu(@RequestBody SpuAuditLog spuAuditLog) {
        return spuAuditLogService.auditSpu(spuAuditLog);
    }

    /**
     * 审核拒绝原因
     * @param spuId
     * @return
     */
    @GetMapping("/auditRejectReason")
    public Result<?> auditRejectReason(@RequestParam(name = "spuId", required = true) Long spuId) {
        QueryWrapper<SpuAuditLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SpuAuditLog::getSpuId, spuId).eq(SpuAuditLog::getAuditStatus, 4).orderByDesc(SpuAuditLog::getCreateTime);
        SpuAuditLog spuAuditLog = spuAuditLogService.getOne(queryWrapper, false);
        return Result.ok(spuAuditLog);
    }

    /**
     * 获取默认供应商商品信息
     * @param spuId
     * @return
     */
    @GetMapping("/defaultSupplierInfos")
    public Result<?> getDefaultSupplierInfos(@RequestParam(name = "spuId", required = true) Long spuId) {
        QueryWrapper<Sku> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Sku::getSpuId, spuId).select(Sku::getId);
        List<Long> skuIds = skuService.listObjs(queryWrapper, skuId -> (Long) skuId);

        QueryWrapper<TSupplierClPro> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TSupplierClPro::getIsDefault, 1).in(TSupplierClPro::getSkuId, skuIds);
        List<TSupplierClPro> supplierClProList = supplierClProService.list(wrapper);
        return Result.ok(supplierClProList);
    }

    @GetMapping("/units")
    public Result<?> getUnits() {
        List<Unit> list = unitService.list();
        return Result.ok(list);
    }
}
